package org.artifact.core.context.bytebuf;

import io.netty.buffer.ByteBuf;
import org.artifact.core.constant.ArtifactErrorCode;
import org.artifact.core.util.LogicUtil;

import java.util.*;

public class NetworkByteBuff extends NettyByteBuf{
    public NetworkByteBuff(ByteBuf buf) {
        super(buf);
    }

    @Override
    public void writeMap(Map value) {
        if (value == null) {
            writeNull();
            return;
        }
        Byte _byte = ProxyContent.MAP_SUB_TYPE.getByKey(value.size());
        if (_byte != null) {
            onWriteByte(_byte);
        } else {
            onWriteByte(ProxyContent.MAP);
            writeInt(value.size());
        }

        Set<Map.Entry> entrys = value.entrySet();
        for (Map.Entry entry : entrys) {
            writeObject(entry.getKey());
            writeObject(entry.getValue());
        }
    }

    @Override
    public void writeCollection(Collection value) {
        if (value == null) {
            writeNull();
            return;
        }
        Byte _byte = ProxyContent.COLLECTION_SUB_TYPE.getByKey(value.size());
        if (_byte != null) {
            onWriteByte(_byte);
        } else {
            onWriteByte(ProxyContent.COLLECTION);
            writeInt(value.size());
        }
        for (Object object : value) {
            writeObject(object);
        }
    }

    @Override
    public Map readMap() {
        byte tag = getTag();

        int size = 0;
        switch (tag) {
            case ProxyContent.NULL:
                return readNull();
            case ProxyContent.MAP:
                skipBytes(Byte.BYTES);
                size = readInt();
            default:
                Integer _int = ProxyContent.MAP_SUB_TYPE.getbyValue(tag);
                LogicUtil.isTrue(ArtifactErrorCode.UNKNOWN_ERROR, _int == null);
                skipBytes(Byte.BYTES);
                size = _int;
        }
        Map map = new HashMap();
        for (int i = 0; i < size; i++) {
            map.put(readObject(), readObject());
        }
        return map;
    }

    @Override
    public Collection<?> readCollection() {
        byte tag = getTag();
        int size = 0;
        switch (tag) {
            case ProxyContent.NULL:
                return readNull();
            case ProxyContent.COLLECTION:
                skipBytes(Byte.BYTES);
                size = readInt();
            default:
                Integer _int = ProxyContent.COLLECTION_SUB_TYPE.getbyValue(tag);
                LogicUtil.isTrue(ArtifactErrorCode.UNKNOWN_ERROR, _int == null);
                skipBytes(Byte.BYTES);
                size = _int;
        }
        String className = readString();
        Collection list = new ArrayList();
        for (int i = 0; i < size; i++) {
            list.add(readObject());
        }
        return list;
    }
}
